//
// Created by yuping.li@calmcar.com on 11/27/23.
//

#ifndef FSM_H
#define FSM_H

#include <functional>
#include <map>
#include <string>


class FSM {
public:
    struct State {
        std::string name;
        std::function<void()> entry;
        std::function<void()> exit;
        std::map<std::string, std::function<void()>> events;
    };

    explicit FSM(State &initial_state) : current_state_ptr(&initial_state) { }

    virtual void enter_initial_state() const {
        if (current_state_ptr->entry) {
            current_state_ptr->entry();
        }
    }

    virtual void start() {
        enter_initial_state();
    }

    virtual void dispatch(const std::string& event) {
        if (current_state_ptr->events.count(event)) {
            current_state_ptr->events[event]();
        }
    }

protected:
    virtual void transit(State& state) {
        if (current_state_ptr->exit) {
            current_state_ptr->exit();
        }
        current_state_ptr = &state;
        if (current_state_ptr->entry) {
            current_state_ptr->entry();
        }
    }

    virtual void transit(State& state, const std::function<void()>& action) {
        if (current_state_ptr->exit) {
            current_state_ptr->exit();
        }
        action();
        current_state_ptr = &state;
        if (current_state_ptr->entry) {
            current_state_ptr->entry();
        }
    }

    virtual void transit(State& state, const std::function<void()>& action, const std::function<bool()>& condition) {
        if (condition()) {
            transit(state, action);
        }
    }

    State* current_state_ptr{nullptr};
};

#endif //FSM_H
